package io.plus.user_interface.server.command.command_handler;

import io.plus.interactive.AsynchronousSocketChannelContext;
import io.plus.user_interface.common.Constants;
import io.plus.user_interface.common.Status;
import io.plus.user_interface.common.packet.Command;
import io.plus.user_interface.common.packet.ResponseMessage;
import io.plus.user_interface.common.packet.auth.AuthRequestMessage;
import io.plus.user_interface.common.protocol.PacketImpl;
import io.plus.user_interface.common.utils.ImKit;
import io.plus.user_interface.common.utils.JsonKit;
import io.plus.user_interface.server.command.AbstractCommandHandler;

/**
 * 鉴权请求消息命令处理器
 */
public class AuthCommandHandler extends AbstractCommandHandler {
    @Override
    public Command command() {
        return Command.auth_request;
    }

    @Override
    public PacketImpl handler(PacketImpl packet, AsynchronousSocketChannelContext asynchronousSocketChannelContext) throws Exception {
        if (packet.getBody() == null) {
            ResponseMessage respBody = new ResponseMessage(Command.auth_response, Status.C10010);
            return ImKit.convertResponsepPacket(respBody, asynchronousSocketChannelContext);
        }
        AuthRequestMessage authReqBody = JsonKit.toBean(packet.getBody(), AuthRequestMessage.class);
        String token = authReqBody.getToken() == null ? "" : authReqBody.getToken();
        String data = token + Constants.authKey;
        authReqBody.setToken(data);
        authReqBody.setCmd(null);
        ResponseMessage respBody = new ResponseMessage(Command.auth_response, Status.C10009).setData(authReqBody);
        return ImKit.convertResponsepPacket(respBody, asynchronousSocketChannelContext);
    }
}
